<script setup>
import {
  Edit, Delete, Link, Download,
} from '@element-plus/icons-vue'
import axios from 'axios';
import { ref } from 'vue'
import { ElMessage, ElMessageBox, ElUpload } from 'element-plus'
import {
  addstaffservice, deletestaffservice, updatestaffservice, getAllservice,
  uploadfileservice, getloadfilenameservice
} from '@/api/companyInfo.js'
import { getchanceandclientservice } from '@/api/client.js'
import {
  addtenderservice, gettendersservice, uploadtenderfileservice, getloadtenderfilenameservice,
  updatetenderservice, deletetenderservice
} from '@/api/tender.js'
//控制添加分类弹窗
const dialogVisible = ref(false)
const dialogVisibleupdate = ref(false)
//分页条数据模型
//const pageNum = ref(1)//当前页
const total = ref(20)//总条数
//const pageSize = ref(3)//每页条数
//文章分类数据模型

//定义变量，控制标题
const title = ref('')
const title2 = ref('上传附件')
//交通路线列表数据模型
const majors = ref([
  { id: 11 }, { id: 23 }
])

const formrefadd = ref(null); //表单校验
const formrefupdate = ref(null); //表单校验
//与后端交互的json数据
const pathmodel = ref({
  name: null,
  type: null,
  chanceid: null,
  clientcompanyname: null,
  projectname: null,
  pet: null,
  phase: null,
  budget: null,
  chancedatetime: null,
  status: null,
  result: null
})

const findmodel = ref({
  pageNum: 1,
  pageSize: 5,
  str: '',
})
const stafflist = async () => {
  console.log(findmodel.value);
  let result = await gettendersservice(findmodel.value);
  console.log(result);
  total.value = result.data.total;
  majors.value = result.data.items;
}
stafflist();
const chanceandclient = ref([])
const chanceslist = async () => {
  let result = await getchanceandclientservice();
  chanceandclient.value = result.data;
  console.log(chanceandclient.value);
}
chanceslist();

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  findmodel.value.pageSize = size;
  stafflist();
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  findmodel.value.pageNum = num;
  stafflist();
}
const cleardata = () => {
  findmodel.value.str = '';
  findmodel.value.pageNum = 1;
  stafflist();
}
//表单校验
const rules = {
  chanceid: [
    { required: true, message: '请选择机会', trigger: 'blur' },
  ],
  type: [
    { required: true, message: '请输入类型', trigger: 'blur' },
  ],
  name: [
    { required: true, message: '请输入投标名称', trigger: 'blur' },
  ],
  status: [
    { required: true, message: '请选择投标状态', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value == '未总结') {
          callback(new Error('请选择投标状态'));
        } else {
          callback();
        }
      }, trigger: 'blur'
    }
  ],
  result: [
    { required: true, message: '请输入投标总结', trigger: 'blur' },
  ],
}
const add = () => {
  for (let key in pathmodel.value) {
    if (pathmodel.value.hasOwnProperty(key)) {
      pathmodel.value[key] = null;
    }
  }
  dialogVisible.value = true
  title.value = '新建投标信息'
}
const addpath = async () => {
  console.log(pathmodel.value);
  formrefadd.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('信息填写不完整！');
    }
    else {
      let result = await addtenderservice(pathmodel.value);
      if (result.code == 0) {
        ElMessage.success("添加成功")
        dialogVisible.value = false;
        stafflist();
      }
      else ElMessage.error(result.message ? result.message : '添加失败')
    }
  });


}
const updatepath = async () => {
  console.log(pathmodel.value);
  formrefupdate.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('信息填写不完整！');
    }
    else {
      let result = await updatetenderservice(pathmodel.value);
      if (result.code == 0) {
        ElMessage.success("修改成功")
        dialogVisibleupdate.value = false;
        stafflist();
      }
      else {
        ElMessage.error(result.message ? result.message : '修改失败')
      }
    }

  })
}

//删除分类
const del = (row) => {
  ElMessageBox.confirm(
    '你确认删除该条信息吗？',
    '温馨提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      //用户点击了确认
      let result = await deletetenderservice(row.id)
      if (result.code != 0) ElMessage.error(result.message ? result.message : '删除失败')
      else ElMessage.success('删除成功')
      //再次调用getAllCategory，获取所有文章分类
      stafflist();
    })
    .catch(() => {
      //用户点击了取消
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
//展示编辑弹窗
const showDialog = (row) => {
  title.value = '投标总结编辑';
  dialogVisibleupdate.value = true;
  //数据拷贝
  Object.keys(row).forEach((key) => {
    if (key != 'chance') pathmodel.value[key] = row[key];//!!!!!!!!!!!!!!!!!!!!关联的实体必须为空
  });
  pathmodel.value.clientcompanyname = row.chance.clientCompany.clientcompanyname
  pathmodel.value.chanceid = row.chanceid
  pathmodel.value.chancename = row.chance.chancename
  pathmodel.value.projectname = row.chance.projectname
}




const fileList = ref([]);
const handleChange = (file, newFileList) => {
  fileList.value = newFileList;
  console.log('Selected files:', fileList.value);
};
const elseid = ref();

const uploadfile = async () => {
  const formData = new FormData();
  fileList.value.forEach(fileItem => {
    formData.append('files', fileItem.raw);
  })
  const formDataArray = Array.from(formData.entries());
  console.log(formDataArray);
  let result = await uploadtenderfileservice(formData, elseid.value)//后端保存了会返回elseid  !!!!!
  if (result.code == 0) {
    ElMessage.success("上传成功")
    dialogVisibleupload.value = false;

  }
  else ElMessage.error(result.message ? result.message : '上传失败')
};
const dialogVisibleupload = ref(false);
const showDialogupload = (row) => {
  fileList.value = [];
  dialogVisibleupload.value = true;
  elseid.value = row.id;
}
const downloadfilesingle = async (filename, delay) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const link = document.createElement('a');
      link.href = `http://localhost:8080/downloadfile/${filename}`;
      link.setAttribute('download', filename);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      resolve();
    }, delay);
  });
}
const download = async (row) => {
  let result = await getloadtenderfilenameservice(row.id)
  let filenames = result.data;
  if (filenames.length == 0) {
    ElMessage.error('没有上传附件')
  }
  else {
    for (let i = 0; i < filenames.length; i++) {
      console.log(filenames[i]);
      await downloadfilesingle(filenames[i], i * 1000)
    }
  }
}



const handleChanceChange = (id) => {
  const cc = chanceandclient.value.find(chanceandclient => chanceandclient.chanceid === id) ?
    chanceandclient.value.find(chanceandclient => chanceandclient.chanceid === id) : null;
  if (cc != null) {
    pathmodel.value.chanceid = cc.chanceid
    pathmodel.value.clientcompanyname = cc.clientcompanyname
    pathmodel.value.phase = cc.phase
    pathmodel.value.budget = cc.budget
    pathmodel.value.pet = cc.pet
    pathmodel.value.projectname = cc.projectname
    pathmodel.value.chancedatetime = cc.chancedatetime
  }
  else {
    pathmodel.value.chanceid = null
    pathmodel.value.clientcompanyname = null
    pathmodel.value.phase = null
    pathmodel.value.budget = null
    pathmodel.value.pet = null
    pathmodel.value.projectname = null
    pathmodel.value.chancedatetime = null
  }
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>投标信息管理</span>
        <div class="extra">
          <el-button type="primary" @click="add">新建投标</el-button>
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form>
      <el-form-item label="查询条件:">
        <el-input v-model="findmodel.str" placeholder="请输入查询内容" style="width: 300px"></el-input>
        <el-button type="primary" @click="stafflist" style="margin-left: 15px;">搜索</el-button>
        <el-button @click="cleardata">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 文章列表 -->
    <el-table :data="majors" style="width: 100%">
      <el-table-column label="投标名称" prop="name"></el-table-column>
      <el-table-column label="投标类型" prop="type"></el-table-column>
      <el-table-column label="机会编号" prop="chanceid"></el-table-column>
      <el-table-column label="投标客户" prop="chance.clientCompany.clientcompanyname"></el-table-column>
      <el-table-column label="项目名称" prop="chance.projectname"></el-table-column>
      <el-table-column label="投标状态" prop="status"></el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button :icon="Download" circle plain type="success" @click="download(row)"></el-button>
          <el-button :icon="Link" circle plain type="info" @click="showDialogupload(row)"></el-button>
          <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="del(row)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination v-model:current-page="findmodel.pageNum" v-model:page-size="findmodel.pageSize"
      :page-sizes="[5, 10, 15, 20]" layout="jumper, total, sizes, prev, pager, next" background :total="total"
      @size-change="onSizeChange" @current-change="onCurrentChange"
      style="margin-top: 20px; justify-content: flex-end" />
  </el-card>

  <!-- 添加新建弹窗 -->
  <el-dialog v-model="dialogVisible" :title="title" width="45%">
    <el-form :model="pathmodel" ref="formrefadd" :rules="rules" label-width="100px" style="padding-right: 30px">
      <div class="basic-info-border">
        <el-row>
          <el-col :span="12">
            <el-form-item label="投标名称" prop="name">
              <el-input v-model="pathmodel.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="投标类型" prop="type">
              <el-select placeholder="请选择..." clearable style="width: 350px" v-model="pathmodel.type">
                <el-option v-for="c in ['A项目', 'B项目', 'C项目']" :key="c" :label="c" :value="c">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="机会名称" prop="chanceid">
              <el-select placeholder="请选择..." clearable style="width: 350px" @change="handleChanceChange"
                v-model="pathmodel.chanceid">
                <el-option v-for="c in chanceandclient" :key="c.chanceid" :label="c.chancename" :value="c.chanceid">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="机会编号">
              <el-input v-model="pathmodel.chanceid" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="投标客户">
              <el-input v-model="pathmodel.clientcompanyname" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="项目名称">
              <el-input v-model="pathmodel.projectname" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="basic-info-border2">
        <el-row>
          <el-col :span="12">
            <el-form-item label="行业">
              <el-input v-model="pathmodel.pet" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="阶段">
              <el-input v-model="pathmodel.phase" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="销售机会日期">
              <el-input v-model="pathmodel.chancedatetime" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="预算">
              <el-input v-model="pathmodel.budget" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addpath"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 添加修改弹窗 -->
  <el-dialog v-model="dialogVisibleupdate" :title="title" width="45%">
    <el-form :model="pathmodel" ref="formrefupdate" :rules="rules" label-width="100px" style="padding-right: 30px">
      <div class="basic-info-border">
        <el-row>
          <el-col :span="12">
            <el-form-item label="投标名称" prop="name">
              <el-input v-model="pathmodel.name" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="投标类型" prop="type">
              <el-select placeholder="请选择..." clearable style="width: 350px" v-model="pathmodel.type" disabled>
                <el-option v-for="c in ['A项目', 'B项目', 'C项目']" :key="c" :label="c" :value="c">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="机会名称" prop="chanceid">
              <el-select placeholder="请选择..." clearable style="width: 350px" @change="handleChanceChange"
                v-model="pathmodel.chanceid" disabled>
                <el-option v-for="c in chanceandclient" :key="c.chanceid" :label="c.chancename" :value="c.chanceid">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="机会编号">
              <el-input v-model="pathmodel.chanceid" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="投标客户">
              <el-input v-model="pathmodel.clientcompanyname" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="项目名称">
              <el-input v-model="pathmodel.projectname" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="basic-info-border3">
        <el-row>
          <el-col :span="24">
            <el-form-item label="投标状态" prop="status">
              <div style="margin-left: 70px;">
                <el-radio label="已中标" v-model="pathmodel.status">已中标</el-radio>
                <el-radio label="未中标" v-model="pathmodel.status">未中标</el-radio>
                <el-radio label="流标" v-model="pathmodel.status">流标</el-radio>
                <el-radio label="废标" v-model="pathmodel.status">废标</el-radio>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="23">
            <el-form-item label="总结" prop="result">
              <el-input type="textarea" :rows="4" placeholder="请输入投标总结..." v-model="pathmodel.result"
                style="width: 800px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisibleupdate = false">取消</el-button>
        <el-button type="primary" @click="updatepath"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>



  <el-dialog v-model="dialogVisibleupload" :title='title2' width="35%">
    <el-upload action="none" class="upload-demo" drag :auto-upload="false" :http-request="httpRequest"
      :file-list="fileList" @change="handleChange">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    </el-upload>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisibleupload = false">取消</el-button>
        <el-button type="primary" @click="uploadfile"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>

</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.basic-info-border {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  right: -10px;
  position: relative;
  padding-top: 30px;
  /* 增加内边距，为标题留出更多空间 */
  margin-right: -10px;
  /* 调整外边距，使边框线不重合 */
}

.basic-info-border::before {
  content: "投标信息";
  position: absolute;
  top: -15px;
  /* 将标题移动到边框上方 */
  left: 10px;

  /* 根据需要调整左边距 */
  background-color: #409EFF;
  color: white;
  padding: 5px;
  border-radius: 3px;
  font-weight: bold;
}

.basic-info-border2 {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  right: -10px;
  position: relative;
  padding-top: 30px;
  /* 增加内边距，为标题留出更多空间 */
  margin-right: -10px;
  /* 调整外边距，使边框线不重合 */
}

.basic-info-border2::before {
  content: "机会信息";
  position: absolute;
  top: -15px;
  /* 将标题移动到边框上方 */
  left: 10px;

  /* 根据需要调整左边距 */
  background-color: #409EFF;
  color: white;
  padding: 5px;
  border-radius: 3px;
  font-weight: bold;
}

.basic-info-border3 {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  right: -10px;
  position: relative;
  padding-top: 30px;
  /* 增加内边距，为标题留出更多空间 */
  margin-right: -10px;
  /* 调整外边距，使边框线不重合 */
}

.basic-info-border3::before {
  content: "投标总结";
  position: absolute;
  top: -15px;
  /* 将标题移动到边框上方 */
  left: 10px;

  /* 根据需要调整左边距 */
  background-color: #409EFF;
  color: white;
  padding: 5px;
  border-radius: 3px;
  font-weight: bold;
}
</style>